package com.jyu.edu.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.jyu.edu.dto.ResultDto;
import com.jyu.edu.dto.TableDto;
import com.jyu.edu.dto.UserDto;
import com.jyu.edu.entity.Role;
import com.jyu.edu.entity.User;
import com.jyu.edu.entityEnum.UserStatusTypeEnum;
import com.jyu.edu.service.UserService;
import com.jyu.edu.utils.AliyunOSSUtil;
import com.jyu.edu.utils.PasswordEntryUtil;

@RestController
public class UserController {
	@Autowired
	UserService userService;
	
	@RequiresPermissions("user_html")
	@RequestMapping("/addUser")
	public ResultDto addUser(User user) {
		if(user.getPassword()==null || user.getPassword().trim().length()==0)
			user.setPassword("123456");
		if(userService.findByUsername(user.getUsername())!=null)
			return new ResultDto("添加失败!用户名已存在!",null,2);
		user.setStatus(UserStatusTypeEnum.unActive.getType());
		user = PasswordEntryUtil.encrypt(user);
		userService.save(user);
		return new ResultDto("添加成功",null,0);
	}
	
	@RequiresPermissions("user_html")
	@RequestMapping("/upUser")
	public ResultDto upUser(long id,String password,String phone,String username,Integer status,
			long roleId) {
		Role role = new Role();
		role.setId(roleId);
		User db_user = userService.getOne(id);
		db_user.setRole(role);
		db_user.setStatus(status);
		if(!db_user.getUsername().equals(username) && userService.findByUsername(username)!=null)
			return new ResultDto("修改失败用户名已被注册!",null,2);
		db_user.setUsername(username);
		if(password==null || password.trim().length()!=0) {
			db_user.setPassword(password);
			db_user = PasswordEntryUtil.encrypt(db_user);
		}
		userService.save(db_user);
		
		return new ResultDto("更新成功",null,0);
	}
	
	@RequiresPermissions("user_html")
	@RequestMapping("/delUser")
	public ResultDto delUser(String ids) {
		String[] idArray = ids.split(",");
		List<User> users = new ArrayList<User>();
		for(String id : idArray) {
			User user = new User();
			user.setId(new Long(id));
			users.add(user);
		}
		userService.delete(users);
		return new ResultDto("删除成功",null,0);
	}
	
	@RequiresPermissions("user_html")
	@RequestMapping("/getUserPage")
	public TableDto<UserDto> getUserPage(Integer pageNumber,Integer pageSize,Long role_id,String search) {
		
		Page<User> pageResult = userService.getUserPage(pageNumber, pageSize, role_id, search);
		List<User> users = pageResult.getContent();
		List<UserDto> userDtos = new ArrayList<UserDto>();
		users.forEach(user->userDtos.add(new UserDto().convert(user)));
		return new TableDto<UserDto>(userDtos,pageResult.getTotalElements());
	}
	
	@RequiresPermissions("user_html")
	@RequestMapping("/user_html")
	public ModelAndView user_html() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/user.html");
		return mv;
	}
	
	@RequiresAuthentication
	@RequestMapping("/getAsyncUser")
	public UserDto getAsyncUser() {
		UserDto userDto = (UserDto) SecurityUtils.getSubject().getSession().getAttribute("userDto");
		User user = userService.getOne(userDto.getId());
		return new UserDto().convert(user);
	}
	
	@RequiresAuthentication
	@RequestMapping("/uploadUserImage")
	public ResultDto uploadUserImage(MultipartFile file) {
		if(file.getSize()>1048576*7)
			return new ResultDto("头像不可大于7M",null,2);
		UserDto userDto = (UserDto) SecurityUtils.getSubject().getSession().getAttribute("userDto");
		User user = userService.getOne(userDto.getId());
		String oldImg = user.getHeadImg();
		if(oldImg!=null && oldImg.startsWith("/oss/")) {
			String oldObjectName =  oldImg.substring(5);
			AliyunOSSUtil.delete(oldObjectName);
		}
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.') + 1);
		try {
			String objectName = AliyunOSSUtil.upload(file.getInputStream(), suffix);
			user.setHeadImg("/oss/" + objectName);
			userService.save(user);
		} catch (IOException e) {
			e.printStackTrace();
			return new ResultDto("上传失败", null, 2);
		}
		return new ResultDto("修改成功,请刷新页面", null, 0);
	}
}
